<template>
  <q-scroll-area class="machine-detail-tab full-height" :thumb-style="thumbStyle">
    <div class="margin-r-20 margin-l-20">
      <div style="line-height: 3">
        <div class="flex justify-between bor-t bor-b" style="padding: 0 20px">
          <div style="flex:1">
            <span class="text-right inline-block" style="width: 120px">
              状态：
            </span>
            <span :style="{color: judgeStatus(params.status, 'color')}">
              {{ judgeStatus(params.status, 'name') }} {{ params.statusDuration + params.statusDurationUnit }}
            </span>
          </div>
          <div style="flex:1">
            <span class="text-right inline-block" style="width: 85px">
              机床型号：
            </span>
            {{ `${params.model || '--'}(${params.ncType})`}}
          </div>
          <div style="flex:1" class="text-right">
            <span>
              操作员：{{ params.operatorName || '--' }}
            </span>
          </div>
        </div>
        <div class="flex justify-between bor-b" style="padding: 0 20px">
          <div style="flex:1">
            <span class="text-right inline-block" style="width: 120px">
              当日机床开动率：
            </span>
            {{ actuateRate }}
          </div>
          <div style="flex:1">
            <span class="text-right inline-block" style="width: 85px">
              总停机时长：
            </span>
            {{ sumStopTime }}
            <!--<span class="show-detail" @click="showDetail">-->
              <!--查看明细-->
            <!--</span>-->
          </div>
          <div style="flex:1" class="text-right">
            <span>
              技术员：
            </span>
            {{ params.technicianName || '--' }}
          </div>
        </div>
      </div>

      <!-- 报警区 -->
      <template v-if="warningData.length > 0">
        <div class="margin-t-20 margin-b-20">
          <q-icon class="iconfont icontubiao-78 font-size-18" style="margin-right: 5px;vertical-align: top;color: #E43434"/>
          <span class="font-size-16" style="color: #E43434">
          报警
          <span class="font-size-12">
            (共{{ warningData.length }}条)
          </span>
        </span>
        </div>
        <q-table
          :data="warningData" :columns="warningColumns"
          row-key="index" class="bor-b myTable scroll my-sticky-virt scroll-table"
          :pagination.sync="pagination" hide-bottom virtual-scroll
          no-data-label="暂无数据"
          color="primary"
          style="margin: 0"
          :style="{height:`${warningData.length>5? '290px':'auto'}`}"
        />
      </template>

      <!-- 报警区End -->
<!--      <template v-if="params.status === 1">-->
      <div v-if="params.status === 1">
      <div class="title bor-b flex justify-between items-center">
        <div> {{ params.materialName ?
          params.materialName  :
          '--' }}：
          {{`${(params.processSort + 1) || '--'}-${params.processName || '--'}` }}</div>
        <div style="width: 374px">
          <div style="line-height: 1.7" class="flex items-center justify-between">
            <div>计划进度：{{ `${params.finishedCount}/${params.jobCount}` }}</div>
            <div>
              {{ getDifferenceCount(params.expectedCount, params.finishedCount, params.jobCount).label }}
              {{ getDifferenceCount(params.expectedCount, params.finishedCount, params.jobCount).value }}
            </div>
          </div>
          <div class="progress-bar">
            <div class="progress-detail" :style="{width: `${params.actualProgress}%`}"></div>
            <div class="tips" :style="{left: `${params.progress}%`}"></div>
          </div>
        </div>
      </div>
      <div class="flex items-center justify-between bor-b">
        <div class="flex" style="height: 144px;padding: 8px 0">
          <div class="flex full-height margin-l-20" style="flex-direction: column">
            <div style="flex: 1;line-height: 64px;height: 64px">
              <q-icon class="iconfont icontubiao-119 font-size-18" style="margin-right: 5px;vertical-align: top"></q-icon>
              <span class="text-bold font-size-18 margin-r-10">当下用时：{{ oeeData.currentTime ? getDuration(oeeData.currentTime) : 0 }}</span>
            </div>
            <div style="flex: 1;line-height: 64px;height: 64px">
              <q-icon class="iconfont icontubiao-119 font-size-18" style="margin-right: 5px;vertical-align: top"></q-icon>
              <span class="text-bold font-size-18 margin-r-10">标准用时：{{ oeeData.cycleTime ? getDuration(oeeData.cycleTime) : 0 }}</span>
            </div>
          </div>
          <div class="flex full-height font-size-14" style="flex-direction: column;margin-left: 40px">
            <div style="flex: 1;line-height: 32px"><span style="width: 100px" class="text-right inline-block">上次循环用时：</span>
              {{ oeeData.lastCycleTime ? getDuration(oeeData.lastCycleTime) : 0 }}
            </div>
            <div style="flex: 1;line-height: 32px"><span style="width: 100px" class="text-right inline-block">最慢用时：</span>
              {{ oeeData.slowestTime ? getDuration(oeeData.slowestTime) : 0 }}
            </div>
            <div style="flex: 1;line-height: 32px"><span style="width: 100px" class="text-right inline-block">最快用时：</span>
              {{ oeeData.fastestTime ? getDuration(oeeData.fastestTime) : 0 }}
            </div>
            <div style="flex: 1;line-height: 32px"><span style="width: 100px" class="text-right inline-block">平均用时：</span>
              {{ oeeData.averageTime ? getDuration(oeeData.averageTime) : 0 }}
            </div>
          </div>
        </div>
        <div class="flex">
          <div ref="oeeRate" style="width: 144px; height: 144px"></div>
          <div class="flex font-size-14" style="flex-direction: column">
            <div style="flex: 1;line-height: 48px">时间开动率(A)：{{ (oeeData.a * 100).toFixed(2) + '%' }}</div>
            <div style="flex: 1;line-height: 48px">性能开动率(P)：{{ (oeeData.p * 100).toFixed(2) + '%' }}</div>
            <div style="flex: 1;line-height: 48px">产品合格率(Q)：{{ (oeeData.q * 100).toFixed(2) + '%' }}</div>
          </div>
        </div>
      </div>
      </div>
      <div v-else style="line-height: 48px" class="title">无作业</div>
      <div class="text-center margin-t-20" style="position: relative">
        <q-toggle v-model="showScale"
                  label="启用缩放"
                  left-label
                  @input="changeScale"
                  style="position: absolute;left: 20px ;top: -10px"
        />
        <span class="text-bold font-size-18">总时间开动率：{{ actuateRate || '--' }}</span>
        <span style="position: absolute;right: 0" class="padding-r-20 font-size-14">
          横坐标：时间
          <span style="margin-left: 30px">
            纵坐标：时间开动率
          </span>
        </span>
      </div>
      <div ref="utilizationRate" class="utilizationRate" style="width: 100%; height: 370px"></div>
    </div>
    <!-- 停机时长明细 -->
    <halt-detail
      ref="downtimeHistory"
      :show="downtimeHistory.show"
      @close="downtimeHistory.show = false"
    />
  </q-scroll-area>
</template>

<script>
import echarts from 'echarts'
import haltDetail from './components/halt-detail'
import {
  getMachineStatusDetails,
  getDowntimeDetails,
  // getMachineExpectedCount,
  getMachineTimeRate,
  getMachineRateChart
} from 'src/boot/status/machine'
import _ from 'lodash'

export default {
  name: 'machine-detail-tab',
  props: {
    msg: {
      type: [Object, String],
      default: () => {}
    },
    details: {
      type: String
    }
  },
  components: {
    haltDetail
  },
  watch: {
    msg (val) {
      // if (val !== undefined) {
      //   const topic = val.destinationName.split('/')
      //   const msg = JSON.parse(val.payloadString)
      //   if (topic[3] === 'productivity') {
      //     this.params.finishedCount = msg.productivity
      //     this.params.actualProgress = this.convertActualProgressProgress(this.params.finishedCount, this.params.jobCount)
      //     // 查询应完成数
      //     this.getMachineExpectedCount(this.params)
      //   } else {
      //     this.params.status = msg.statusCode
      //     if (msg.alarmCount) {
      //       // 查询新的报警信息
      //       this.getMachineStatusDetails(this.params)
      //     }
      //   }
      // }
    },
    details () {
      this.init()
    }
  },
  data () {
    return {
      showScale: false, // 是否可以缩放
      // 报警记录表列
      warningColumns: [
        { name: 'id', field: 'id', label: '报警编号', align: 'left' },
        { name: 'type', field: 'type', label: '报警类型', align: 'left' },
        { name: 'cause', field: 'cause', label: '报警原因', align: 'left' },
        { name: 'duration', field: 'duration', label: '报警持续时长', align: 'center' }
      ],
      // 报警记录表数据
      warningData: [],
      // 表格不分页
      pagination: {
        rowsPerPage: 0
      },
      oeeData: {}, // OEE源数据
      oeeRate: {}, // OEE Echarts
      utilizationChart: {}, // 开动率 Echarts
      utilizationData: {}, // 开动率源数据
      // 停机时长明细
      downtimeHistory: {
        show: false
      },
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      // 接收父组件传值
      params: null,
      // 当日机床开动率
      actuateRate: 0,
      // 机床状态源数据
      statusOptions: [],
      // 总停机时长
      sumStopTime: null
    }
  },

  created () {
    this.init()
  },

  mounted () {
    window.addEventListener('resize', () => {
      this.oeeRate.resize()
      this.utilizationChart.resize()
    })
  },

  methods: {
    // 图表缩放
    changeScale () {
      let option = _.cloneDeep(this.utilizationChart.getOption())
      // console.log(this.showScale, 'this.showScale')
      option.dataZoom[0].disabled = !this.showScale
      this.utilizationChart.clear()
      this.utilizationChart.setOption(option)
    },
    // 初始化数据
    init () {
      // this.$q.loading.show()

      // // hiding in 2s
      // this.timerLoading = setTimeout(() => {
      //   this.$q.loading.hide()
      //   this.timerLoading = void 0
      // }, 500)
      // 冲状态枚举中取出机床状态数组
      const newArr = Object.entries(this.Enums.MACHINES_STATUS)
        .map(entry => {
          return {
            value: entry[1].value,
            label: entry[1].desc,
            color: entry[1].color
          }
        })
      this.statusOptions.push(...newArr)

      // 处理列表页传入的初始值
      const val = JSON.parse(this.details)
      console.log(val, 666)
      val.progress = this.convertExpectedCountProgress(val.expectedCount, val.jobCount)
      val.actualProgress = this.convertActualProgressProgress(val.finishedCount, val.jobCount)
      this.params = val
      this.getMachineStatusDetails(this.params)
      this.getMachineTimeRate(this.params)
      this.getMachineRateChart(this.params)
    },

    /**
     * 获取实际预计差值
     * @param {number} expectedCount 预计完成数量
     * @param {number} finishedCount 实际完成数量
     * @param {number} jobCount 总计划数
     * @return {{}}
     */
    getDifferenceCount (expectedCount, finishedCount, jobCount) {
      let label = ''
      let value = null
      // 若预计产量大于总数
      // 返回总数-实际的绝对值
      if (parseInt(expectedCount) > parseInt(jobCount)) {
        (parseInt(jobCount) - parseInt(finishedCount)) > 0 ? label = '落后数：' : label = '领先数：'
        value = Math.abs(parseInt(jobCount) - parseInt(finishedCount))
      } else {
        // 若实际产量小于总数
        // 返回预计-实际的绝对值
        (parseInt(expectedCount) - parseInt(finishedCount)) > 0 ? label = '落后数：' : label = '领先数：'
        value = Math.abs(parseInt(expectedCount) - parseInt(finishedCount))
      }

      return {
        value: value,
        label: label
      }
    },

    // 获取机床详情数据（开动率，停机时长，报警记录）
    getMachineStatusDetails (val) {
      // 获取本页接口数据
      getMachineStatusDetails(val.boxId, val.id).then(res => {
        this.actuateRate = `${(res.data.actuateRate * 100).toFixed(2)}%`
        this.sumStopTime = this.getDuration(res.data.sumStopTime)
        res.data.alarms.forEach((o, index) => {
          o.duration = this.getDuration(o.duration)
          o.index = index
        })
        this.warningData = res.data.alarms
      })
    },

    // // 获取应完成数量
    // getMachineExpectedCount (val) {
    //   getMachineExpectedCount(val.boxId, val.id).then(res => {
    //     this.params.expectedCount = parseInt(res.data.expectedCount)
    //     this.params.progress = this.convertExpectedCountProgress(parseInt(res.data.expectedCount), this.params.jobCount)
    //   })
    // },

    getMachineTimeRate (val) {
      getMachineTimeRate(val.boxId, val.id).then(res => {
        this.oeeData = res.data
        // 进哥说这个值特殊。。该接口内的作废改从上一页拿
        this.oeeData.cycleTime = this.params.cycleTime
      }).then(() => {
        this.SetEchart()
      })
    },

    getMachineRateChart (val) {
      getMachineRateChart(val.boxId, val.id).then(res => {
        res.data.value = res.data.value.map(item => {
          return item * 100
        })
        res.data.totalRate = res.data.totalRate * 100
        this.utilizationData = res.data
      }).then(() => {
        this.utilizationRateChart()
      })
    },

    // 显示停机明细
    showDetail () {
      this.downtimeHistory.show = true
      getDowntimeDetails().then(res => {
        res.data.forEach(o => {
          o.duration = this.getDuration(o.duration)
        })
        this.$refs.downtimeHistory.assignment(res.data)
      })
    },

    // 绘制OEE echarts
    SetEchart () {
      const _this = this
      const oee = (_this.oeeData.oee * 100).toFixed(2) > 100 ? 100 : (_this.oeeData.oee * 100).toFixed(2)
      // 基于准备好的dom，初始化echarts实例
      _this.oeeRate = echarts.init(_this.$refs.oeeRate)
      // 绘制图表
      const option = {
        title: {
          text: 'OEE',
          left: 'center',
          top: '80%',
          textStyle: {
            fontWeight: 'normal',
            fontSize: '18',
            color: '#5F77FD'
          }
        },
        series: [{
          name: '装备制造',
          type: 'pie',
          clockWise: false,
          radius: [37, 45],
          itemStyle: {
            normal: {
              color: '#5F77FD',
              shadowColor: '#5F77FD',
              shadowBlur: 0,
              label: {
                show: false
              },
              labelLine: {
                show: false
              }
            }
          },
          hoverAnimation: false,
          center: ['50%', '42%'],
          data: [{
            value: oee,
            label: {
              normal: {
                formatter: function () {
                  return oee + '%'
                },
                position: 'center',
                show: true,
                textStyle: {
                  fontSize: '18',
                  fontWeight: 'bold',
                  color: '#5F77FD'
                }
              }
            }
          }, {
            value: 100 - oee,
            name: 'invisible',
            itemStyle: {
              normal: {
                color: '#d3d3d3'
              },
              emphasis: {
                color: '#d3d3d3'
              }
            }
          }]
        }]
      }
      _this.oeeRate.setOption(option)
    },

    // 绘制开动率Echarts
    utilizationRateChart () {
      // console.log('重绘chart了吗')
      // 基于准备好的dom，初始化echarts实例
      this.utilizationChart = echarts.init(this.$refs.utilizationRate)
      // 绘制图表
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              type: 'dashed'
            }
          },
          formatter: function (params, ticket, callback) {
            var htmlStr = ''
            var value = (params[0].value).toFixed(2)
            var color = params[0].color

            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' + color + ';"></span>'
            htmlStr += value + '%'

            htmlStr += '</div>'
            return htmlStr
          }
        },
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0
          }
        ],
        grid: {
          left: 50,
          right: 20,
          top: 20,
          bottom: 20
        },
        xAxis: [{
          type: 'category',
          data: this.utilizationData.time,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisTick: {
            show: false
          }
        }],
        yAxis: [{
          type: 'value',
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisLabel: {
            formatter: function (val) {
              return val + '%'
            },
            fontSize: 14
          },
          axisTick: {
            show: false
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#333'
            }
          },
          nameTextStyle: {
            color: '#999'
          },
          splitArea: {
            show: false
          }
        }],
        series: [{
          name: '开动率',
          type: 'line',
          data: this.utilizationData.value,
          lineStyle: {
            normal: {
              width: 5,
              color: '#5F77FD',
              shadowColor: 'rgba(95, 119, 253, 0.3)',
              shadowBlur: 10,
              shadowOffsetY: 20
            }
          },
          symbolSize: 15,
          itemStyle: {
            normal: {
              color: '#5F77FD',
              borderWidth: 3,
              borderColor: '#5F77FD'
            },
            emphasis: {
              color: '#5F77FD',
              borderColor: '#5F77FD'
            }
          },
          smooth: true
        }]
      }
      this.utilizationChart.setOption(option)
    },

    // 转换预期产量进度条,传入应完工数量与派工数量
    convertExpectedCountProgress (expectedCount, jobCount) {
      let progress = null
      if (parseInt(expectedCount) / parseInt(jobCount) * 100 <= 0) {
        progress = 0
      } else if (parseInt(expectedCount) / parseInt(jobCount) * 100 >= 100) {
        progress = 100
      } else {
        progress = parseInt(expectedCount) / parseInt(jobCount) * 100
      }
      return progress
    },

    // 转换实际产量进度条,传入实际产量与派工数量
    convertActualProgressProgress (finishedCount, jobCount) {
      let progress = null
      if (parseInt(finishedCount) / parseInt(jobCount) * 100 <= 0) {
        progress = 0
      } else if (parseInt(finishedCount) / parseInt(jobCount) * 100 >= 100) {
        progress = 100
      } else {
        progress = parseInt(finishedCount) / parseInt(jobCount) * 100
      }
      return progress
    },

    // 转换停机总时常
    getDuration (second) {
      var days = Math.floor(second / 86400)
      var hours = Math.floor((second % 86400) / 3600)
      var minutes = Math.floor(((second % 86400) % 3600) / 60)
      var seconds = Math.floor(((second % 86400) % 3600) % 60)
      var duration = days + '天' + hours + '小时' + minutes + '分' + seconds + '秒'
      return duration
    },

    // 过滤状态枚举
    judgeStatus (statusCode, type) {
      if (type === 'name') {
        let name = ''
        this.statusOptions.forEach(o => {
          if (o.value === statusCode) {
            name = o.label
          }
        })
        return name
      } else {
        let color = ''
        this.statusOptions.forEach(o => {
          if (o.value === statusCode) {
            color = o.color
          }
        })
        return color
      }
    }
  }
}
</script>

<style scoped lang="stylus">
  .font-size-16 {
    font-size 16px
  }
  .font-size-14 {
    font-size 14px
  }
  .font-size-12 {
    font-size 12px
  }
  .bor-b {
    border-bottom $border
  }
  .bor-t {
    border-top $border
  }
  .title{
    border-radius:6px 6px 0px 0px;
    background-color #F3F3F3
    margin-top 20px
    height 48px
    padding 0 20px
  }
  .progress-bar{
    width 100%
    height 14px
    background-color #d3d3d3
    border-radius 4px
    position relative
    .progress-detail {
      height inherit
      background-color $secondary /* 不支持线性的时候显示 */
      background-image linear-gradient(to right, $secondary,#51a8e1, $primary);
      border-radius inherit
    }
    .tips{
      height inherit
      width 2px
      background-color $warning
      position absolute
      top 0
    }
  }
  .tooltip{
    display inline-block
    width 10px
    height 10px
    border-radius 50%
    background-color #5F77FD
  }
  .show-detail{
    cursor pointer
    color $primary
    margin-left 5px
  }
</style>
